/*
 * Wazuh Vulnerability scanner - Scan Orchestrator
 * Copyright (C) 2015, Wazuh Inc.
 * Jan 22, 2024.
 *
 * This program is free software; you can redistribute it
 * and/or modify it under the terms of the GNU General Public
 * License (version 2) as published by the FSF - Free Software
 * Foundation.
 */

#ifndef _FETCH_ALL_DATA_FROM_GLOBAL_DB_HPP
#define _FETCH_ALL_DATA_FROM_GLOBAL_DB_HPP

#include "chainOfResponsability.hpp"
#include "loggerHelper.h"
#include "scanContext.hpp"
#include "socketDBWrapper.hpp"
#include "vulnerabilityScanner.hpp"
#include "wazuhDBQueryBuilder.hpp"

/**
 * @brief Orchestrates queries over the global Wazuh system
 *
 * This class is responsible for managing the execution of queries within the global Wazuh environment.
 *
 * @tparam TScanContext scan context type.
 */
template<typename TScanContext = ScanContext>
class TFetchFromGlobalDB final : public AbstractHandler<std::shared_ptr<TScanContext>>
{

public:
    /**
     * @brief Construct a new global fetch object
     */
    explicit TFetchFromGlobalDB() = default;

    /**
     * @brief Handles request and passes control to the next step of the chain.
     *
     * The `handleRequest` method processes incoming requests, executes queries in the Wazuh-DB, and forwards the
     * query response to a sub-orchestration component. The handling involves several steps:
     *
     * 1. It instantiates the socketWrapper for the Wazuh-DB if it hasn't been created.
     * 2. Executes a query in the Wazuh-DB to fetch data.
     * 3. Sends the query response to sub-orchestration as a scan context.
     *
     * @param data A shared pointer to the input data containing details of the query request.
     *
     * @note This function may interact with the Wazuh-DB, perform query operations, and create a scan context
     *       to pass to the sub-orchestration. It may also throw exceptions in the event of errors.
     *
     * @return A shared pointer to a `TScanContext` object representing the query response.
     */
    std::shared_ptr<TScanContext> handleRequest(std::shared_ptr<TScanContext> data) override
    {
        // Instance the socketWrapper for wazuhDb
        static SocketDBWrapper wdbSocketWrapper(WDB_SOCKET);

        // Execute query
        nlohmann::json response;
        wdbSocketWrapper.query(WazuhDBQueryBuilder::builder().global().selectAll().fromTable("agent").build(),
                               response);

        // Send response to suborchestration
        std::variant<const SyscollectorDeltas::Delta*,
                     const SyscollectorSynchronization::SyncMsg*,
                     const nlohmann::json*>
            variantData;
        variantData = &response;
        auto context = std::make_shared<TScanContext>(variantData);

        return AbstractHandler<std::shared_ptr<TScanContext>>::handleRequest(std::move(context));
    }
};

using FetchFromGlobalDB = TFetchFromGlobalDB<>;

#endif // _FETCH_ALL_DATA_FROM_GLOBAL_DB_HPP
